package com.yan.core.utils;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClassUtils implements ResourceLoaderAware {

    /**
     * Spring容器注入
     */
    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    //classpath*:com/yan/**/*.class
    public List<Class<?>> getAllClass(String path) {
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = new Resource[0];
        try {
            resources = resolver.getResources(path);
        } catch (IOException e) {
            System.err.println("path 路径加载失败 请检查" + path);
            System.err.println("请求参考：path路径示例：classpath*:com/yan/**/*.class");
        }

        List<Class<?>> result = new ArrayList<>();
        for (Resource r : resources) {
            MetadataReader reader = null;
            try {
                reader = metaReader.getMetadataReader(r);
                Class<?> aClass = Class.forName(reader.getClassMetadata().getClassName());
                result.add(aClass);
            } catch (IOException e) {
                System.err.println("资源加载失败");
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                System.err.println("类创建失败：" + reader.getClassMetadata().getClassName());
                e.printStackTrace();
            }
        }
        return result;
    }

    public void println(){
        System.out.println("-----------------------");
    }

    @Override
    public String toString() {
        return "----------------------ClassUtils{" +
                "resourceLoader=" + resourceLoader +
                '}';
    }
}

